package com.heima.wemedia.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.wemedia.dtos.WmMaterialDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.utils.threadlocal.WmThreadLocalUtil;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;

@Service
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {

    @Autowired
    private FileStorageService fileStorageService;

    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    @Autowired
    private WmMaterialMapper wmMaterialMapper;

    /**
     * 素材上传
     *
     * @param file
     * @return
     */
    @Override
    @Transactional
    public ResponseResult upload(MultipartFile file) {
        //1.上传图片到minio中
        try {
            // 调用 FileStorageService 的上传方法，这里测试类用的是 uploadImgFile，根据实际需求选择
            String filePath = fileStorageService.uploadImgFile("", file.getOriginalFilename(), file.getInputStream());
            WmMaterial wmMaterial = new WmMaterial();
            wmMaterial.setUserId(WmThreadLocalUtil.getUser().getId());
            wmMaterial.setUrl(filePath);
            wmMaterial.setIsCollection((short) 0);
            wmMaterial.setCreatedTime(Date.from(LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant()));
            this.save(wmMaterial);
            return ResponseResult.okResult(wmMaterial);
        } catch (Exception e) {
            // 可根据具体异常细分不同的错误码返回，这里简单处理
            return ResponseResult.errorResult(501, "文件上传失败");
        }
    }

    /**
     * 查询素材列表
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult list(WmMaterialDto dto) {
        Page<WmMaterial> wmMaterialPage = new Page<>(dto.getPage(), dto.getSize());

        Integer userId = WmThreadLocalUtil.getUser().getId();
        if (dto.getIsCollection()==0){
            Page<WmMaterial> page = this.lambdaQuery()
                    .eq(userId != null, WmMaterial::getUserId, userId)
                    .page(wmMaterialPage);
            long total = page.getTotal();
            List<WmMaterial> records = page.getRecords();
            PageResponseResult responseResult = new PageResponseResult(dto.getPage(), dto.getSize(), Integer.valueOf(StrUtil.toString(total)));
            responseResult.setData(records);
            return responseResult;
        }
        Page<WmMaterial> page = this.lambdaQuery()
                .eq(dto.getIsCollection() != null, WmMaterial::getIsCollection, dto.getIsCollection())
                .eq(userId != null, WmMaterial::getUserId, userId)
                .page(wmMaterialPage);
        long total = page.getTotal();
        List<WmMaterial> records = page.getRecords();
        PageResponseResult responseResult = new PageResponseResult(dto.getPage(), dto.getSize(), Integer.valueOf(StrUtil.toString(total)));
        responseResult.setData(records);
        return responseResult;
    }

    /**
     * 删除素材
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult del(Integer id) {
        LambdaQueryWrapper<WmMaterial> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(WmMaterial::getId, id);
        wmMaterialMapper.delete(wrapper);

         return ResponseResult.okResult(200, "删除成功");
    }

    /**
     * 取消收藏
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult cancel(Integer id) {
        this.lambdaUpdate().eq(WmMaterial::getId, id)
                .set(WmMaterial::getIsCollection, 0)
                .update();
        return ResponseResult.okResult(200, "操作成功");
    }

    /**
     * 收藏
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult collect(Integer id) {
                this.lambdaUpdate().eq(WmMaterial::getId, id)
                        .set(WmMaterial::getIsCollection, 1)
                        .update();
        return ResponseResult.okResult(200, "操作成功");
    }
}
